<?php
declare (strict_types = 1);

namespace app\command;

use app\admin\controller\Qbapi;
use app\admin\controller\Trapi;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Rhilip\Bencode\Bencode;
use think\admin\model\SystemDownload;
use think\admin\model\SystemQueueLog;
use think\admin\model\SystemSites;
use think\admin\model\SystemConfig;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class SearchReSeed extends \think\admin\Command

{
    protected function configure()
    {
        $this->setName('search')
            ->setDescription('the search command');
    }

    protected function execute(Input $input, Output $output)
    {
        $jconfig  = SystemConfig::mQuery()->db()->where('type', 'jackett')->find();
        if(!$jconfig || !isset($jconfig['value'])){
          $msg = '未配置jackett数据，请点击头像配置参数,结束运行程序';
          $this->msg($msg);
          $this->setQueueSuccess($msg);
        }
        $downloadIds = $this->queue->data;
        foreach ($downloadIds as $downloadId){
          $downloadResult = SystemDownload::mQuery()->db()->where('id', $downloadId)->find();
          $siteResult = SystemSites::mQuery()->db()->whereIn('id', array_map('intval', explode(',', $downloadResult['reseed_sites'])))->select();
          $search = [];
          if ($downloadResult) {
            $msg = '正在检索种子库';
            $this->msg($msg);
            $this->setQueueProgress($msg, '10');
            foreach (scandir($downloadResult['save_path']) as $file_name) {
                if (pathinfo($file_name, PATHINFO_EXTENSION) == 'torrent') {
                    $file_path = $downloadResult['save_path'] . '/' . $file_name;
                    try {
                        $torrent_data = file_get_contents($file_path);
                        $torrent = Bencode::decode($torrent_data);
                        $info = $torrent['info'];
                        $torrent_name = $info['name'];
                        $size = 0;
                        if (isset($info['length'])) {
                          $size = $info['length'];
                        }else{
                          for ($i = 0; $i < count($info['files']); $i++) {
                            $size += $info['files'][$i]['length'];
                          }
                        }
                        $size = round($size / 1073741824, 2);
                        $title_names = explode('.', $info['name']);
                        if (count($title_names) > 5) {
                            $search_name = $title_names[1] . " " . $title_names[2] . " " . $title_names[3];
                        }else{
                          continue;
                        }
                        $info_sha1 = sha1(Bencode::encode($info));
                        // 判断元素是否已存在  
                        $exists = false;  
                        foreach ($search as $item) {  
                            if ($item['infoHash'] == $info_sha1) {  
                                $exists = true;  
                                break;  
                            }  
                        } 
                        if(!$exists){
                            $search[] = ['titleName' => $torrent_name, 'searchName' => $search_name, 'infoHash' => $info_sha1, 'size' => $size];
                        }
                    } catch (\Exception $e) {
                        continue;
                    }
                }
            }
            $msg = '种子目录中检索到'. count($search) . '个种子';
            $this->msg($msg);
            $this->setQueueProgress($msg,'30');
            if(count($search) == 0){
                continue;
            }
            if($downloadResult['type'] == 1){
              $qbapi = new Qbapi($downloadResult);
              foreach ($search as $i) {
                  $data = $this->guzzlePost($i['searchName'],$jconfig);
                  foreach ($data['Results'] as $d) {
                      if ($i['size'] == round($d['Size'] / 1073741824, 2)) {
                          $torrent_info = $qbapi->getTorrentsInfo($i['infoHash'], 'completed');
                          if (!empty($torrent_info)) {
                              $save_path = $torrent_info[0]['save_path'];
                              $msg = '保存目录：' . $save_path;
                              $this->msg($msg);
                              $this->setQueueProgress($msg,'70');
                              if ($qbapi->addTorrent(
                                  $d['Link'],
                                  $save_path,
                                  $downloadResult['is_skip_hash'],
                                  $downloadResult['is_paused']) == 'Ok.') {
                              }
                          }
                          $msg = '匹配到种子：'.$d['Guid'];
                          $this->msg($msg);
                          $this->setQueueProgress($msg,'70');
                      }
                  }
                  sleep(10);
              }
            }else{
              $trapi = new Trapi($downloadResult);
              foreach ($search as $i) {
                $data = $this->guzzlePost($i['searchName'],$jconfig);
                foreach ($data['Results'] as $d) {
                    if ($i['size'] == round($d['Size'] / 1073741824, 2)) {
                        $torrent_info = $trapi->getTorrentsInfo($i['infoHash']);
                        if (!empty($torrent_info)) {
                            $save_path = $torrent_info['arguments']['torrents'][0]['downloadDir'];
                            $msg = '保存目录：' . $save_path;
                            $this->msg($msg);
                            $this->setQueueProgress($msg,'70');
                            $result = $trapi->addTorrent(
                              $d['Link'],
                              $save_path,
                              $downloadResult['is_paused']);
                            if ($result['result'] == 'success') {
                              $msg = '匹配到种子：'.$d['Guid'];
                              $this->msg($msg);
                              $this->setQueueProgress($msg,'70');
                            }
                        }
                    }
                }
                sleep(10);
              }
            }  
          }else {
            $msg = "下载器ID不存在！请检查是否删除了对应下载器！";
            $this->msg($msg);
            $this->setQueueProgress($msg, '100');
          }
        }
        $this->setQueueSuccess('结束运行程序');
    }
    public function guzzlePost($query,$jconfig)
    {
        $client = new Client();
        $url = $jconfig['name'].'/api/v2.0/indexers/all/results?apikey='.$jconfig['value'].'&Query=' . $query;
        try {
            $response = $client->request("GET", $url, [
                'timeout' => 30,
                'verify' => false,
            ]);
        } catch(\Exception $e){
          $msg = 'jackett请求时间超过30秒或地址错误或key配置错误';
          $this->msg($msg);
          $this->setQueueProgress($msg, '70');
          return ['Results'=>[]];
        }

        $response_json = json_decode((string) $response->getBody(), true);
        $response->getBody()->close();
        return $response_json;
    }

    public function msg($message){
      // SystemQueueLog::mQuery()->db()->data(['msg'=>$message])->insert();
    }
}
